import { useEffect, useRef, useState } from 'react';
import { Card } from '@shopify/polaris';
import './Canvas.css';

// 声明全局 fabric 对象
declare global {
  interface Window {
    fabric: any;
  }
}

interface DesignElement {
  id: string;
  position: { x: number; y: number };
  transform: {
    scale: number;
    rotation: number;
  };
  icon?: {
    url: string;
  };
}

interface DesignData {
  baseProductID: string;
  elements: DesignElement[];
  background?: string;
}

interface CanvasProps {
  width: number;
  height: number;
  designData?: DesignData;
  onElementAdd?: (element: any) => void;
  onElementUpdate?: (element: any) => void;
  onElementSelect?: (element: any) => void;
  onCanvasReady?: (canvas: any) => void;
}

// 扩展 fabric.Object 类型
declare module 'fabric' {
  namespace fabric {
    interface Object {
      id?: string;
    }
  }
}

export const Canvas: React.FC<CanvasProps> = ({ 
  width, 
  height,
  designData,
  onElementAdd, 
  onElementUpdate,
  onElementSelect,
  onCanvasReady
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [canvas, setCanvas] = useState<any>(null);

  // 修改 useEffect，改进画布初始化
  useEffect(() => {
    const initializeCanvas = () => {
      if (!window.fabric || !canvasRef.current) {
        console.log('Waiting for fabric.js and canvas element...'); // 调试信息
        return;
      }

      console.log('Initializing canvas...'); // 调试信息
      
      // 确保 canvas 元素已经挂载并且有尺寸
      if (canvasRef.current.width === 0 || canvasRef.current.height === 0) {
        console.log('Canvas element not ready, waiting...'); // 调试信息
        return;
      }

      let fabricCanvas: any = null;

      try {
        // 确保 fabric.Canvas 是一个构造函数
        if (typeof window.fabric.Canvas !== 'function') {
          console.error('Fabric.js Canvas constructor not available');
          return;
        }

        // 创建画布实例
        fabricCanvas = new window.fabric.Canvas(canvasRef.current, {
          width,
          height,
          selection: true,
          preserveObjectStacking: true,
          renderOnAddRemove: true,
          stateful: true,
          backgroundColor: '#ffffff' // 设置白色背景
        });

        // 确保 canvas 上下文已经创建
        if (!fabricCanvas.getContext()) {
          console.error('Failed to get canvas context');
          return;
        }

        // 立即设置画布实例
        setCanvas(fabricCanvas);

        // 加载 T恤背景图片
        console.log('Loading T-shirt image...'); // 调试信息
        window.fabric.Image.fromURL('/assest/image/ts.jpeg', (img: any) => {
          if (!fabricCanvas || !fabricCanvas.getContext()) {
            console.error('Canvas context lost during image loading');
            return;
          }

          console.log('T-shirt image loaded successfully:', img); // 调试信息
          
          // 计算缩放比例，保持图片比例
          const canvasWidth = width;
          const canvasHeight = height;
          const imgWidth = img.width;
          const imgHeight = img.height;
          
          // 计算缩放比例，使图片适应画布
          const scale = Math.min(
            canvasWidth / imgWidth * 0.8, // 留出一些边距
            canvasHeight / imgHeight * 0.8
          );
          
          // 设置图片属性
          img.scale(scale);
          
          // 计算居中位置
          const left = (canvasWidth - imgWidth * scale) / 2;
          const top = (canvasHeight - imgHeight * scale) / 2;
          
          img.set({
            left,
            top,
            selectable: false,
            evented: false,
            originX: 'left',
            originY: 'top'
          });

          // 将图片设置为背景
          fabricCanvas.setBackgroundImage(img, () => {
            if (fabricCanvas && fabricCanvas.getContext()) {
              fabricCanvas.renderAll();
              console.log('T-shirt image set as background'); // 调试信息
            }
          }, { crossOrigin: 'anonymous' }); // 添加跨域支持
        }, { crossOrigin: 'anonymous' }); // 添加跨域支持

        // 配置画布事件
        fabricCanvas.on('object:modified', (e: any) => {
          const element = e.target;
          if (element && onElementUpdate) {
            onElementUpdate({
              id: element.id || '',
              position: { 
                x: element.left || 0, 
                y: element.top || 0 
              },
              transform: {
                scale: element.scaleX || 1,
                rotation: element.angle || 0
              }
            });
          }
        });

        // 添加选择事件
        fabricCanvas.on('selection:created', (e: any) => {
          if (e.target && onElementSelect) {
            onElementSelect(e.target);
          }
        });

        fabricCanvas.on('selection:updated', (e: any) => {
          if (e.target && onElementSelect) {
            onElementSelect(e.target);
          }
        });

        fabricCanvas.on('selection:cleared', () => {
          if (onElementSelect) {
            onElementSelect(null);
          }
        });

        // 添加对象移动事件
        fabricCanvas.on('object:moving', () => {
          fabricCanvas.renderAll();
        });

        // 添加对象缩放事件
        fabricCanvas.on('object:scaling', () => {
          fabricCanvas.renderAll();
        });

        // 添加对象旋转事件
        fabricCanvas.on('object:rotating', () => {
          fabricCanvas.renderAll();
        });

        return () => {
          console.log('Disposing canvas...'); // 调试信息
          if (fabricCanvas && fabricCanvas.getContext()) {
            fabricCanvas.dispose();
          }
        };
      } catch (error) {
        console.error('Error initializing canvas:', error);
      }
    };

    // 如果 fabric.js 已经加载，立即初始化
    if (window.fabric && typeof window.fabric.Canvas === 'function') {
      initializeCanvas();
    } else {
      // 否则等待 fabric.js 加载完成
      const checkFabric = setInterval(() => {
        if (window.fabric && typeof window.fabric.Canvas === 'function') {
          clearInterval(checkFabric);
          initializeCanvas();
        }
      }, 100);

      // 清理定时器
      return () => clearInterval(checkFabric);
    }
  }, [width, height]); // 添加 width 和 height 作为依赖项

  // 修改 addElementFromOutside 方法
  const addElementFromOutside = (elementData: any) => {
    console.log('Adding element to canvas:', elementData); // 调试信息
    if (!canvas || !window.fabric) {
      console.error('Canvas or fabric not initialized');
      return;
    }

    console.log('Loading image from URL:', elementData.url); // 调试信息
    
    // 创建新的图片对象
    const img = new window.fabric.Image(elementData.url, {
      crossOrigin: 'anonymous',
      onload: () => {
        console.log('Image loaded successfully:', img); // 调试信息
        
        // 重新检查 canvas 状态
        if (!canvas || !canvas.getContext()) {
          console.error('Canvas context lost during image loading');
          return;
        }

        // 计算初始大小
        const maxSize = Math.min(width, height) * 0.2; // 初始大小为画布的 20%
        const scale = Math.min(
          maxSize / img.width,
          maxSize / img.height
        );

        img.scale(scale);
        
        // 设置图片属性
        img.set({
          left: elementData.dropPosition ? elementData.dropPosition.x : width / 2,
          top: elementData.dropPosition ? elementData.dropPosition.y : height / 2,
          originX: 'center',
          originY: 'center',
          id: elementData.id,
          hasControls: true,
          hasBorders: true,
          lockRotation: false,
          lockScalingX: false,
          lockScalingY: false,
          lockMovementX: false,
          lockMovementY: false,
          transparentCorners: false,
          cornerColor: 'rgba(102,153,255,0.8)',
          cornerSize: 12,
          padding: 5,
        });

        // 直接添加新图片，不清除画布
        canvas.add(img);
        canvas.setActiveObject(img);
        canvas.renderAll();
        
        if (onElementAdd) onElementAdd(img);
      },
      onerror: (err: any) => {
        console.error('Error loading image:', err); // 调试信息
      }
    });
  };

  // 将方法暴露给 window 对象
  useEffect(() => {
    if (canvas && window.fabric) {
      console.log('Canvas initialized, exposing addElementToCanvas method'); // 调试信息
      (window as any).addElementToCanvas = (elementData: any) => {
        console.log('addElementToCanvas called with:', elementData); // 调试信息
        if (!canvas || !window.fabric) {
          console.error('Canvas or fabric not initialized');
          return;
        }
        addElementFromOutside(elementData);
      };
      
      if (onCanvasReady) {
        onCanvasReady(canvas);
      }
    } else {
      console.log('Canvas not ready yet'); // 调试信息
      // 如果之前暴露过方法，现在移除它
      if ((window as any).addElementToCanvas) {
        delete (window as any).addElementToCanvas;
      }
    }
  }, [canvas, onCanvasReady]);

  useEffect(() => {
    if (canvas && designData) {
      // 清除画布
      canvas.clear();

      // 添加背景图片
      if (designData.background) {
        window.fabric.Image.fromURL(designData.background, (img: any) => {
          img.scaleToWidth(canvas.width!);
          canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
        });
      }

      // 添加所有元素
      designData.elements.forEach(element => {
        if (element.icon) {
          window.fabric.Image.fromURL(element.icon.url, (img: any) => {
            // 设置位置
            img.set({
              left: element.position?.x || 0,
              top: element.position?.y || 0,
              angle: element.transform?.rotation || 0,
              scaleX: element.transform?.scale || 1,
              scaleY: element.transform?.scale || 1,
              id: element.id,
              selectable: true,
              hasControls: true
            });

            // 添加到画布
            canvas.add(img);
            canvas.renderAll();
          });
        }
      });
    }
  }, [canvas, designData]);

  return (
    <Card>
      <div 
        className="canvas-container"
        onDragOver={(e) => {
          e.preventDefault();
          e.dataTransfer.dropEffect = 'copy';
        }}
        onDrop={(e) => {
          e.preventDefault();
          const iconData = JSON.parse(e.dataTransfer.getData('application/json'));
          if (iconData) {
            // 获取画布容器的位置信息
            const canvasContainer = e.currentTarget;
            const rect = canvasContainer.getBoundingClientRect();
            
            // 计算相对于画布的位置
            const x = e.clientX - rect.left - (iconData.offsetX || 0);
            const y = e.clientY - rect.top - (iconData.offsetY || 0);
            
            // 添加元素时使用计算出的位置
            addElementFromOutside({
              ...iconData,
              dropPosition: { x, y }
            });
          }
        }}
      >
        <canvas ref={canvasRef} />
      </div>
    </Card>
  );
}; 